const http = require('http');
const path = require('path');
const fs = require('fs');
const url = require('url');
http.createServer((request, response) => {
    let requestUrl = url.parse(request.url).pathname;
    let staticUrl = path.join(__dirname, requestUrl === '/' ? 'index.html' :  requestUrl);
    let notFoundPage = path.join(__dirname, '404.html');
    let fileExt = path.extname(staticUrl) ? path.extname(staticUrl) : path.extname(notFoundPage);
    //根据文件后缀设置响应头，默认content-type: text/plain
    fs.readFile(path.join(__dirname, 'mime.txt'),'utf8', (err, chunk) => {
        if(err) {
            response.end(err);
        }else{
            let mimeObj = JSON.parse(chunk);
            let contentType = mimeObj.hasOwnProperty(fileExt) ? mimeObj[fileExt] : 'text/plain';
            response.writeHead(200, {
                'Content-Type': contentType
            });
            fs.readFile(staticUrl, (err, chunk) => {
                if(err) {
                    if(err.code === 'ENOENT') {
                        fs.readFile(notFoundPage, (err, chunk) => {
                            if(err){
                                response.end(err.message);
                            }else{
                                response.end(chunk);
                            }
                        })
                    }else {
                        response.end(err.message);
                    }
                }else {
                    response.end(chunk);
                }
            })
        }
    });
    //设置响应头
}).listen(3000, '127.0.0.1', ()=> {
    console.log('服务已启动')
});